package com.ai.platform.core.annotation.aop;

import com.ai.platform.common.util.AiPlatformUtil;
import com.ai.platform.core.annotation.CheckUserSession;
import com.ai.platform.model.dto.Input;
import com.ai.platform.system.entity.SysUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Auther: yeyingsheng
 * @Date: 2018/5/26 20:49
 * @Description: 用户登录session检查
 */
@Aspect
@Component
public class CheckUserSessionAop {

    private Logger logger = LoggerFactory.getLogger(CheckUserSessionAop.class);


    @Pointcut(value = "@annotation(com.ai.platform.core.annotation.CheckUserSession)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object doService(ProceedingJoinPoint point) throws Throwable {
        //获取拦截的方法名
        Signature signature = point.getSignature();
        MethodSignature methodSignature;
        if (!(signature instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        methodSignature = (MethodSignature) signature;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
        //获取注解
        CheckUserSession checkUserSession = currentMethod.getAnnotation(CheckUserSession.class);
        boolean isCheck=false;
        if(null!=checkUserSession){
            if(checkUserSession.value()){
                isCheck=true;
            }
        }else {
            isCheck=true;
        }
        if(isCheck){
            logger.debug("校验用户登录SESSION...");
            //拦截方法的参数
            Input input = null;
            Object[] params = point.getArgs();
            for (Object object : params) {
                if (object instanceof Input) {
                    input = (Input) object;
                }
            }
            if (input == null) {
                throw new IllegalArgumentException("input参数为空");
            }
            SysUser sysUser= (SysUser) AiPlatformUtil.getSessionObj(input,SysUser.class);
            if (null == sysUser) {
                throw new IllegalArgumentException("用户未登录");
            }
        }
        return point.proceed();

    }


}
